package user

import (
	"encoding/json"
	"errors"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	weixin2 "github.com/flipped-aurora/gin-vue-admin/server/utils/weixin"

	"github.com/flipped-aurora/gin-vue-admin/server/model/entity/user"
	"github.com/flipped-aurora/gin-vue-admin/server/model/entity/user/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/entity/user/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/entity/weixin"
)

type XkUserService struct {
}

// 解密手机信息
func (service *XkUserService) ParserWxPhone(params request.MobileStrut) (phoneInfo weixin.WxUser, err error) {

	newWxUser := weixin.WxUser{}

	code := params.Code
	wxMap, errTip := weixin2.GetOpenid(code)
	if len(errTip) != 0 {
		return newWxUser, errors.New("微信请求超时")
	}
	data, err := weixin2.MobileDncrypt(params.EncryptedData, wxMap["session_key"], params.Iv)
	if err != nil {
		return newWxUser, err
	}
	var s = map[string]interface{}{}
	json.Unmarshal([]byte(data), &s)
	mobile := s["phoneNumber"].(string) // 无法将数据（类型接口{}）转换为字符串类型：需要类型断言

	newWxUser.Openid = wxMap["openid"]
	newWxUser.SessionKey = wxMap["session_key"]
	newWxUser.UnionId = wxMap["unionid"]
	newWxUser.Mobile = mobile

	return newWxUser, nil
}

// 根据手机号查询用户
func (service *XkUserService) GetUserByPhone(mobile string) (baseUser user.User, err error) {
	baseUser = user.User{}
	err = global.GVA_DB.Where("mobile = ?", mobile).Find(&baseUser).Error
	return baseUser, err
}

// 注册游客

func (service *XkUserService) CreatVisiter(wxInfo weixin.WxUser) (baseUser user.User, err error) {
	baseUser = user.User{}

	baseUser.WechatOpenId = wxInfo.Openid
	baseUser.UnionId = wxInfo.UnionId
	baseUser.Mobile = wxInfo.Mobile
	baseUser.UserName = wxInfo.Mobile

	baseUser.Name = "访客"
	baseUser.UserType = "visit"
	baseUser.Avatar = "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
	baseUser.Status = 1
	baseUser.Note = "游客注册"
	baseUser.Sex = 0
	baseUser.Description = "这家伙很懒，什么都没留下~"

	err = global.GVA_DB.Create(&baseUser).Error

	wxUser := user.WxUser{}
	wxUser.UserId = baseUser.ID
	wxUser.Mobile = wxInfo.Mobile
	wxUser.Name = "访客"
	wxUser.Note = "游客注册"

	err = global.GVA_DB.Create(&wxUser).Error
	return baseUser, err
}

/*
*
查询作者信息
*/

func (userService *XkUserService) FindAuthorPage(req *request.AuthorPageReq) (resp response.XkAuthorResp, err error) {
	// 获取globaldb
	var authorResponses []response.AuthorResopnse
	var total int64
	// 执行sql json.
	db := global.GVA_DB.Table("xk_user t1, xk_user_author t2").
		Select("t1.id, t1.avatar, t1.nickname, t1.account, t2.author_name").
		Where("t1.id = t2.user_id AND t2.`status` = 1 AND t1.forbbiden = 0")

	if len(req.Keyword) > 0 {
		db.Where("t1.nickname like ? or t1.account like ? or t2.author_name like ?", "%"+req.Keyword+"%", "%"+req.Keyword+"%", "%"+req.Keyword+"%")
	}

	//if req.UserId != -1 {
	//	db.Where("t1.id = ?", req.UserId)
	//}

	err = db.Count(&total).Error
	if err != nil {
		return resp, err
	}

	err = db.Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize).Scan(&authorResponses).Error
	if err != nil {
		return resp, err
	}

	resp.PageNum = req.PageNum
	resp.PageSize = req.PageSize
	resp.Total = total
	// 返回列表信息
	resp.List = authorResponses
	//结果返回
	return resp, nil
}
